<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-08
 * Time: 10:19
 */

namespace App\Http\Common;

use App\Models\WyKefuOpenid;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;

/**
 * http 请求
 * Class HttpRequest
 * @package App\Http\Common
 */
class HttpRequest
{
    //创建静态私有的变量保存该类对象
    static private $instance;
    //参数
    private $config;
    //防止直接创建对象
    private function __construct($config){
        $this -> config = $config;
    }
    //防止克隆对象
    private function __clone(){
    }
    static public function getInstance($config=null){
        //判断$instance是否是Uni的对象
        //没有则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /**
     * get方法
     * @param $url 请求的网站
     * @return mixed
     */
    public function get($url){
        $info=curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info,CURLOPT_URL,$url);
        $output= curl_exec($info);
        curl_close($info);
        return $output;
    }

    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    function post2($url, $post_data) {
        try{
            $token = json_decode(Redis::get('saveTemplateToken'));
            $token = $token?MyUtils::sg($token,'token'):"";
            $postdata = http_build_query($post_data);
            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => sprintf("token:%s\r\n", $token).
                        "Content-type: application/x-www-form-urlencoded\r\n",
                    'content' => $postdata,
                    'timeout' => 15 * 60 // 超时时间（单位:s）
                )
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            return $result;
        }catch (\Exception $e){
            return true;
        }
    }

    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param $data
     * @return string
     */
    public function post1($url,$data)
    {
        $token = json_decode(Redis::get('saveTemplateToken'));
        MyUtils::writeLogs('测试发送模板','测试发送模板$token',99,json_encode($token));
        $token = $token?MyUtils::sg($token,'token'):"";
        $headers = ['token'=>$token];
        MyUtils::writeLogs('测试发送模板','测试发送模板$token',99,json_encode($headers));
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        MyUtils::writeLogs('测试发送模板','测试发送模板$token',99,json_encode($content));
        return $content;
    }

    /**
     * 数组映射
     * @param $arr
     * @param $keys
     * @return array
     */
    public function arrayMap($arr,$keys){
        $res = [];
        foreach ($arr as $k=>$v){
            if (array_key_exists($k,$keys)){
                $res[$keys[$k]] = $v;
            }
        }
        return $res;
    }

    /**
     * 通知客服
     * @param $requestArr
     * @param $data
     * @param $type
     */
    public function noticeKefu($requestArr,$data,$type){
        $content = $this->arrayMap($requestArr,$data);
        // 客服的openid 列表
        $WyKefuOpenids = WyKefuOpenid::all();
        $token = json_decode(Redis::get('saveTemplateToken'));
        $token = $token?MyUtils::sg($token,'token'):"";
        foreach ($WyKefuOpenids as $k=>$v){
            try{
                $WyKefuOpenid = $v->app_openid;
                $params = [];
                $params['token'] = $token;// token
                $params['appid'] = 'wxb5956d4f809ffd61';// 小程序appid
                $params['urlPost'] = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';// 小程序appid
                $params['params']['touser'] = $WyKefuOpenid;// 公众号的openid
                $params['params']['msgtype'] = 'text';
                $params['params']['text']['content'] = $type."\n".$this->dealArrTo($content);
                $url = 'https://wxopen.thebanfang.com/admin/weixin/wxapp/post';
                $res = HttpRequest::getInstance()->post2($url,$params);
            }catch (Exception $e){
            }
        }
    }

    /**
     * 把数组数据处理成容易理解的数据 key=>value 变成 key:value
     * @param $arr
     * @return string
     */
    public function dealArrTo($arr){
        $res = "";
        foreach ($arr as $k=>$v){
            $res .= $k.":".$v."\n";
        }
        return $res;
    }
}
